﻿/*文件注释
 * ===============================================================================
 * 说明：
 * 获取ajax提交json数组数据的ValueProviderFactory 
 * ajax提交json数组到controller 需要用类获取json数组数据
 * 作者：曾永佑
 * 版本：V1.0
 * 创建日期：2013-06-30
 * 完成日期： 
 * 修改纪录：  
 * ===============================================================================
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace SRF.UI
{
    /// <summary>
    /// 获取ajax提交json数组数据的ValueProviderFactory 
    /// ajax提交json数组到controller 需要用类获取json数组数据 
    /// 需要在ValueProviderFactories添加该实例
    /// ValueProviderFactories.Factories.Add(new SRF.Core.JsonArrayValueProviderFactory());
    /// </summary>
public class JsonArrayValueProviderFactory : ValueProviderFactory
{
    public override IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        var formValues = controllerContext.HttpContext.Request.Form;

        var values = new Dictionary<string, object>();
        Regex regex = new Regex(@"\[[A-Za-z]*\]");
        for (int i = 0; i < formValues.Count; i++)
        {
            string key = formValues.Keys[i];
            var matchs = regex.Matches(key);
            if (matchs.Count > 0)
            {
                foreach (Match match in matchs)
                {
                    if (match.Value != "[]")
                        key = key.Replace(match.Value, "." + match.Value.Trim('[', ']'));
                }
                if (key.EndsWith("[]"))
                    values.Add(key.Replace("[]", ""), formValues.GetValues(i));
                else
                    values.Add(key, formValues[i]);
            }
        }

        return new DictionaryValueProvider<object>(values, System.Globalization.CultureInfo.InvariantCulture);
    }
}
}